package cn.kow.kmall.controller;

import cn.kow.kmall.common.enums.OrderServiceStatusEnum;
import cn.kow.kmall.common.enums.KmallResultEnum;
import cn.kow.kmall.common.enums.OrderServiceTypeEnum;
import cn.kow.kmall.core.exception.ServiceException;
import cn.kow.kmall.core.response.KmallResult;
import cn.kow.kmall.pojo.dto.OrderAfterSaleCreateDTO;
import cn.kow.kmall.pojo.dto.OrderAfterSaleQueryDTO;
import cn.kow.kmall.pojo.entity.Order;
import cn.kow.kmall.pojo.entity.OrderAfterSale;
import cn.kow.kmall.pojo.entity.OrderItem;
import cn.kow.kmall.pojo.vo.ServiceOrderVO;
import cn.kow.kmall.service.OrderAfterSaleService;
import cn.kow.kmall.service.OrderRefundService;
import cn.kow.kmall.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2019-05-13 15:27
 * @Modified By:
 */
@Slf4j
@RestController
@RequestMapping("/order/after-sale")
public class OrderAfterSaleController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderRefundService orderRefundService;

    @Autowired
    private OrderAfterSaleService orderAfterSaleService;


    /**
     * 创建服务单
     *
     * @param createDTO
     * @return
     */
    @PostMapping("/create")
    public KmallResult afterSaleCreate(@RequestBody OrderAfterSaleCreateDTO createDTO) {
        String orderNo = createDTO.getOrderNo();
        Long skuId = createDTO.getSkuId();
        Integer applyNum = createDTO.getApplyNum();
        Integer serviceType = createDTO.getType();

        Order order = orderService.getOrder(orderNo);
        // 订单商品
        List<OrderItem> itemList = orderService.listOrderItem(order.getOrderNo());
        OrderItem orderItem = itemList.stream().filter(i -> i.getSkuId().equals(skuId)).findFirst()
                .orElseThrow(() -> new ServiceException(KmallResultEnum.ITEM_NOT_FIND));

        OrderAfterSale afterSale = new OrderAfterSale();
        afterSale.setServiceType(serviceType);
        afterSale.setUid(order.getUid());
        afterSale.setOrderNo(orderNo);
        afterSale.setApplyNum(applyNum);
        afterSale.setItemId(orderItem.getItemId());
        afterSale.setSkuId(orderItem.getSkuId());
        afterSale.setItemName(orderItem.getItemName());
        afterSale.setItemSpec(orderItem.getItemSpec());
        afterSale.setItemPic(orderItem.getItemPic());
        afterSale.setUnitPrice(orderItem.getUnitPrice());
        afterSale.setApplyReason(createDTO.getApplyReason());
        afterSale.setApplyContent(createDTO.getApplyContent());
        afterSale.setReturnWay(createDTO.getReturnWay());
        afterSale.setServiceStatus(OrderServiceStatusEnum.UN_AUDIT.getValue());
        // 计算退货金额
        int itemFee;
        Integer buyNum = orderItem.getBuyNum();
        Integer refundNum = orderItem.getRefundNum();
        if (buyNum.equals(refundNum)) {
            return KmallResult.fail("商品可退货数量为0");
        }
        Integer payFee = orderItem.getPayFee();
        if (buyNum.equals(applyNum)) {
            itemFee = payFee;
        } else {
            itemFee = payFee/buyNum * applyNum;
        }
        afterSale.setItemFee(itemFee);

        orderAfterSaleService.create(afterSale);
        if (OrderServiceTypeEnum.REFUND_ITEM.getType().equals(serviceType)) {
            orderItem.setRefundNum(orderItem.getRefundNum() + applyNum);
            orderService.updateOrderItem(orderItem);
        }
        return KmallResult.success();
    }


    /**
     * 商品订单列表
     *
     * @param uid
     * @param type  申请中，1处理中，2已完成，3申请记录
     * @param page
     * @return
     */
    @GetMapping("/list")
    public KmallResult list(
            @RequestAttribute Long uid,
            @Range(max = 3, message = "type值错误")
            @RequestParam(defaultValue = "0") Integer type,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        OrderAfterSaleQueryDTO queryDTO = new OrderAfterSaleQueryDTO();
        queryDTO.setUid(uid);
        queryDTO.setPage(page);
        queryDTO.setSize(size);
        if (type < 3) {
            queryDTO.setServiceStatus(type);
        }
        Page<OrderAfterSale> orderPage = orderAfterSaleService.listByPage(queryDTO);
        List<ServiceOrderVO> voList = new ArrayList<>();
        if (orderPage.hasContent()) {
            for (OrderAfterSale order : orderPage.getContent()) {
                ServiceOrderVO vo = new ServiceOrderVO();
                BeanUtils.copyProperties(order, vo);
                if (order.getServiceStatus() == 0) {
                    vo.setServiceStatus("申请中");
                    vo.setAuditMessage("服务单已提交，客服处理中");
                } else if (order.getServiceStatus() == 1) {
                    vo.setServiceStatus("处理中");
                    vo.setAuditMessage("服务单审核通过，系统处理中");
                } else if (order.getServiceStatus() == 2) {
                    vo.setServiceStatus("完成");
                    vo.setAuditMessage("服务已完成，感谢您的支持");
                } else if (order.getServiceStatus() == 3) {
                    vo.setServiceStatus("失败");
                    vo.setAuditMessage("服务单审核失败，感谢您的支持");
                }
                voList.add(vo);
            }
        }

        return KmallResult.success().put("list", voList)
                .put("type", type)
                .put("page", page)
                .put("size", size)
                .put("hasMore", orderPage.hasNext());
    }
}
